package com.peach.controller.DeviceManage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.peach.domain.DeviceManage.Device;
import com.peach.domain.ResultVO;
import com.peach.domain.UserManage.CurrentUser;
import com.peach.domain.UserManage.User;
import com.peach.service.DeviceManage.DeviceApplication;
import com.peach.service.UserManage.UserApplication;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/mdm")
public class CheckInController {

    @Autowired
    private DeviceApplication deviceApplication;

    @Autowired
    private UserApplication userApplication;

    private Device device = new Device();

    private String inOrOut = null;

    @RequestMapping(value = "/checkIn",method = RequestMethod.PUT)
    public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, DocumentException {
        res.setHeader("Access-Control-Allow-Origin", "*");

        StringBuffer sb = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(),"UTF-8"));
            String s ;
            while((s = br.readLine()) != null) {
                sb.append(s+"\n");
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        SAXReader reader = new SAXReader();
        ByteArrayInputStream inputStream = new ByteArrayInputStream(sb.toString().getBytes());
        InputStreamReader ir = new InputStreamReader(inputStream);
       Document document = reader.read(ir);

        Element element = document.getRootElement();
        Element dict = element.element("dict");

        //设备请求服务器 判断请求类型并获取xml中的参数
        for ( Iterator j = dict.elementIterator(); j.hasNext();) {
            Element key = (Element) j.next();
            if ("MessageType".equals(key.getData().toString())){
                Element messageType =(Element) j.next();
                if ("Authenticate".equals(messageType.getData().toString())){
                    inOrOut = "checkIn1";
                }else if ("TokenUpdate".equals(messageType.getData().toString())){
                    inOrOut = "checkIn2";
                }else if ("CheckOut".equals(messageType.getData().toString())){
                    inOrOut = "checkOut";
                }
            }
            if ("UDID".equals(key.getData().toString())){
                //这样可以找到制定节点的下一个兄弟节点的值 比如找到udid下的string节点的值 即设备udid的值，并存储进数据库可以用这个方法
                Element udidEle =(Element) j.next();
                device.setUdid(udidEle.getData().toString());
            }

            if ("PushMagic".equals(key.getData().toString())){
                Element pushMagicEle =(Element) j.next();
                device.setPushMagic(pushMagicEle.getData().toString());
            }

            if ("Token".equals(key.getData().toString())){
                Element tokenEle =(Element) j.next();
                //TOKEN需要去掉头尾的空字符串
                device.setToken(tokenEle.getData().toString().trim());
            }

            if ("UnlockToken".equals(key.getData().toString())){
                Element unLockTokenELe = (Element) j.next();
                device.setUnLockToken(unLockTokenELe.getText());
            }
        }
        //TODO:若请求处理太慢，则把进行当前准备安装配置文件的账号id的目的数据库改成redis，加快速度。
        //设备第一次checkIn
        if ("checkIn1".equals(inOrOut)){
            //设备第一次checkIn
            CurrentUser curUser= userApplication.selectCurrentUser();
            String currentUser = curUser.getCurrentUser();
            String nickName = curUser.getNickName();
            System.out.println("设备第一次checkIn,"+"当前用户为"+currentUser+"，当前安装的设备的昵称为："+nickName);
            device.setOwner(currentUser);
            System.out.println("准备存储数据库的参数："+device.toString());
            deviceApplication.insertDeviceWithUDID(device);
        }
        //设备第二次checkIn
        else if ("checkIn2".equals(inOrOut)){
            System.out.println("设备第二次checkIn");
            deviceApplication.updatePushMagicAndToken(device);
            userApplication.deleteCurrentUser();
        }
        //设备移除配置文件
        else if ("checkOut".equals(inOrOut)){
            System.out.println("设备移除配置文件");
            deviceApplication.deleteDeviceWithUDID(device);
        }
    }

//    @RequestMapping("/test")
//    @ResponseBody
//    public ResultVO test(HttpServletRequest req,HttpServletResponse res){
//
//        String data = req.getParameter("data");
//
//        List<Device> devices = JSON.parseArray(data,Device.class);
//
//        System.out.println(devices);
//        ResultVO rs = new ResultVO();
//        rs.setStatus("1");
//
//        return rs;
//    }
}
